package com.ponhu.ea2.goodsCenter.provider.biz.impl;

import com.ponhu.ea2.entity.GoodsDataCreateorupdateLog;
import com.ponhu.ea2.goodsCenter.provider.biz.InvokeStockCenterInterfaceService;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsDataCreateorupdateLogService;
import com.ponhu.ea2.goodsCenter.provider.utils.DingTalkHandler;
import com.ponhu.ea2.stockcenter.service.bms.StockForGoodsCenterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

@Slf4j
@Service
public class InvokeStockCenterInterfaceServiceImpl implements InvokeStockCenterInterfaceService {
    @DubboReference(version = "1.0.0", check = false)
    private StockForGoodsCenterService stockForGoodsCenterService;

    @Resource
    private GoodsDataCreateorupdateLogService goodsDataCreateorupdateLogService;

    @Resource
    DingTalkHandler dingTalkHandler;

    @Override
    public boolean createAndInitUnRealStockData(Long goodsId, Long inventoryId, String inventoryCode, int stockNumber) {
        if (stockForGoodsCenterService.createAndInitUnRealStockData(goodsId, inventoryId, inventoryCode, stockNumber)) {
            log.info("库存中心-初始化虚拟类库存成功");
            return true;
        } else {
            log.error("库存中心-初始化虚拟类库存失败");
            return false;
        }

    }

    @Override
    public boolean createAndInitRealStockData(Long goodsId, Long inventoryId, String inventoryCode) {
        Boolean bool = false;
        try {
            bool = stockForGoodsCenterService.createAndInitRealStockData(goodsId, inventoryId, inventoryCode, 0);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("推送库存中心失败：{}", e);
        } finally {
            if (!bool) {
                GoodsDataCreateorupdateLog stock = goodsDataCreateorupdateLogService
                        .getLog(inventoryCode, "stock");
                if (ObjectUtils.isEmpty(stock)) {
                    goodsDataCreateorupdateLogService.saveLog("stock",
                            "推送库存中心初始化库存失败",
                            inventoryCode.toString(), null);
                }
                log.error("同步库存中心初始化库存失败,失败数据:货品id为{},商品id为{}", inventoryId, goodsId);
                // 对接钉钉保障提醒
                String msg = dingTalkHandler.getDingDingMsgForStock(inventoryCode, goodsId);
                dingTalkHandler.sendMsg(msg, new ArrayList());
            }
        }
        return bool;
    }
}
